package com.atguigu.test.boot.bean;

import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.SystemEnvironmentPropertySource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import org.springframework.web.context.support.StandardServletEnvironment;

import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * @author zp
 * @version 1.0
 * @description: 自定义的环境变量注入类
 * @date 2023/2/7 19:43
 */
public class MyStandardServletEnvironment extends StandardServletEnvironment {
    public static final String APPLICATION_FILE_URL = "application.properties";
    public static final String APPLICATION = "application";
    /**
     * @description:  自定义读取配置资源方式
     * @author zp
     * @date: 2023/2/10 19:32
     * @param propertySources
     */
    @Override
    protected void customizePropertySources(MutablePropertySources propertySources) {
        try {
            propertySources.addLast(
                    new SystemEnvironmentPropertySource(APPLICATION, getApplicationProperties()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        super.customizePropertySources(propertySources);
    }
    /**
     * @description:  获取 application.properties 文件当中的参数 缓存到环境变量当中
     * @author zp
     * @date: 2023/2/10 19:33
     * @return Map<Object>
     */
    private Map<String,Object> getApplicationProperties() throws IOException {
        Map<String,Object> map = new HashMap<>();
        Properties properties = new Properties();
        InputStream resourceAsStream = MyStandardServletEnvironment.class.getClassLoader().getResourceAsStream(APPLICATION_FILE_URL);
        properties.load(resourceAsStream);
        Enumeration<?> enumeration = properties.propertyNames();
        while (enumeration.hasMoreElements()){
            String key = (String) enumeration.nextElement();
            String value = properties.getProperty(key);
            key = key.toLowerCase();
            map.put(key,value);
        }
        return map;
    }
}
